import SyntaxHighlighter from '@/components/SyntaxHighlighter'
import { useEffect } from 'react'

const data = [
  {
    id: 1,
    name: "用户管理",
    pid: 0,
  },
  {
    id: 2,
    name: "角色管理",
    pid: 0,
  },
  {
    id: 3,
    name: "菜单管理",
    pid: 12,
  },
  {
    id: 4,
    name: "用户删除",
    pid: 1,
  },
  {
    id: 11,
    name: "用户角色",
    pid: 5,
  },
  {
    id: 5,
    name: "用户添加",
    pid: 1,
  },
  {
    id: 6,
    name: "用户更新",
    pid: 1,
  },
  {
    id: 7,
    name: "角色添加",
    pid: 2,
  },
  {
    id: 8,
    name: "角色更新",
    pid: 2,
  },
  {
    id: 9,
    name: "菜单添加",
    pid: 3,
  },
  {
    id: 10,
    name: "菜单更新",
    pid: 3,
  },
];


const code1 = `
  [
    {
      id: 1,
      name: "用户管理",
      pid: 0,
    },
    {
      id: 2,
      name: "角色管理",
      pid: 0,
    },
    {
      id: 3,
      name: "菜单管理",
      pid: 12,
    },
    {
      id: 4,
      name: "用户删除",
      pid: 1,
    },
    {
      id: 11,
      name: "用户角色",
      pid: 5,
    },
    {
      id: 5,
      name: "用户添加",
      pid: 1,
    },
    {
      id: 6,
      name: "用户更新",
      pid: 1,
    },
    {
      id: 7,
      name: "角色添加",
      pid: 2,
    },
    {
      id: 8,
      name: "角色更新",
      pid: 2,
    },
    {
      id: 9,
      name: "菜单添加",
      pid: 3,
    },
    {
      id: 10,
      name: "菜单更新",
      pid: 3,
    },
  ]
`

const code2 = `
  const setData = () => {
    const map = new Map();
    const result = []

    data.forEach(item => {
      map.set(item.id, { ...item, children: [] })
    })

    console.log(map)

    data.forEach(item => {
      const node = map.get(item.id)
      const parentId = node.pid

      if (map.has(parentId)) {
        const parentNode = map.get(parentId)
        parentNode.children.push(node)
      } else {
        result.push(node)
      }
    })

    console.log('result', result)
  }
`

function ArrayToTree() {

  const setData = () => {
    const map = new Map();
    const result = []

    data.forEach(item => {
      map.set(item.id, { ...item, children: [] })
    })

    console.log(map)

    data.forEach(item => {
      const node = map.get(item.id)
      const parentId = node.pid

      if (map.has(parentId)) {
        const parentNode = map.get(parentId)
        parentNode.children.push(node)
      } else {
        result.push(node)
      }
    })

    console.log('result', result)
  }

  useEffect(() => {
    setData()
  }, [])

  return (
    <div>
      <p>将下列数据转组合成嵌套形式（tree）</p>
      <SyntaxHighlighter children={code1} />
      <p>代码实现逻辑</p>
      <SyntaxHighlighter children={code2} />
    </div>
  )
}

export default ArrayToTree